#include <QDebug>
#include "udock.h"
#include "defaultwindowfinder.h"

namespace UDock {

DockManager::DockManager():dragging(0),m_previewer(0),
    m_state(State::DEFAULT),m_dragtolerance(30){

}

void DockManager::mouseDown(IDockItem *widget, const Point &point, const Point &offset){
    dragging = widget;
    this->offset = offset;
    this->dragstart = point;
    if (widget->undocked()){
        startDrag(point);
        return mouseMove(widget,point);
    }
}

void DockManager::mouseMove(IDockItem *widget, const Point &point){

    if (widget != dragging)
        return;

    if (m_state & State::DRAGGING){
        m_previewer->moveWidget(widget, point,offset);
    }
    else if (dragstart.manHattanDistance(point) > m_dragtolerance){
       startDrag(point);
       return mouseMove(widget,point);
    }

    std::unordered_set<Window> ignores = previewer()->previewWidgets();
    ignores.insert(widget->window());
    Window target_window = UDock::DefaultWindowFinder::getDefaultWindowFinder()
            ->windowFromPoint(point,ignores);
    qDebug()<< target_window;
    //TODO: show dock indicators
    IBaseDock* basedock_target = m_layoutmanager->baseDockFromPoint(target_window,point);

    if (basedock_target == 0){
        m_previewer->unHover();
        return;
    }
    DockOption dockoption = m_previewer->hoveredIndicator(point, basedock_target);
    if (dockoption != 0){
        qDebug() << dockoption;
    }
    IDockItem* dockitem_target = m_layoutmanager->itemFromPoint(basedock_target, point);
    dockoption = m_previewer->hoveredIndicator(point, dockitem_target);
}

void DockManager::mouseUp(IDockItem *widget, const Point &point){
    m_previewer->hidePreviews();
    Point pt = point;
    pt -= offset;
    widget->move(pt);
    dragging = 0;
    m_state = static_cast<State>(m_state & ~State::DRAGGING);

}

void DockManager::startDrag(const Point & point)
{
     m_state = static_cast<State>(m_state | State::DRAGGING);
     m_previewer->previewBasicDocks(dragging);

}

}
